<?php
namespace p5\http;

class AccessHandler
{
    private $token = "";

    public function encrypt()
    {
        $params = ["timestamp" => $this->get_milli_time(), "random_string" => uniqid()];
        $string = $params["timestamp"] . $params["random_string"] . $this->token;
        $md5 = md5($string);
        $params["md5"] = $md5;
        return $params;
    }

    public function verify($params)
    {
        if (empty($params)) {
            return false;
        }
        if (!array_key_exists("timestamp", $params) || !array_key_exists("random_string", $params) || !array_key_exists("md5", $params)) {
            return false;
        }
        // 检查时长
        $current_time = $this->get_milli_time();
        if (abs($current_time * 1 - $params["timestamp"]) > 500000) {
            return false;
        }
        $string = $params["timestamp"] . $params["random_string"] . $this->token;
        $md5 = md5($string);
        if ($md5 != $params["md5"]) {
            return false;
        }
        return true;
    }

    public function verify_request()
    {
        return $this->verify($this->get_parameters(["timestamp", "random_string", "md5"]));
    }

    public function get_milli_time()
    {
        $time_test = microtime();
        list($ten_thousand, $sec) = explode(" ", $time_test);
        $time = ((float)$ten_thousand + (float)$sec);
        return round($time * 1000);
    }

    public function get_parameters($names = array())
    {
        $matrix = $_REQUEST;
        if (!isset($matrix) || !is_array($matrix)) {
            if ($_SERVER["REQUEST_METHOD"] == "POST") {
                $matrix = $_POST;
            } else if ($_SERVER["REQUEST_METHOD"] == "GET") {
                $matrix = $_GET;
            }
        }
        if (empty($names)) {
            $names = array_keys($matrix);
        } else if (!is_array($names)) {
            $names = explode(",", $names);
        }

        $result = array();
        for ($i = 0; $i < count($names); $i++) {
            $name = $names[$i];
            if (array_key_exists($name, $matrix)) {
                $result[$name] = $matrix[$name];
            }
        }
        return $result;
    }

    /**
     * @return string
     */
    public function getToken()
    {
        return $this->token;
    }

    /**
     * @param string $token
     */
    public function setToken($token)
    {
        $this->token = $token;
    }

}